/*
* 访问后端的统一接口，调用示例:
* import {Request} from 'request'
* Request({
*   url: '/getNum',
*   method: 'post',
*   data: myParams
* }).then(res => {
    mydata = res
})
* 失败状态码会在此统一检测，返回200状态response的data部分
*/
import axios from 'axios'
import { ElMessage } from 'element-plus'
import {ReLogin} from "../router"
   
const Request = axios.create({
  baseURL: 'http://localhost:5000',
  withCredentials: true,
  timeout: 10000
})

// request interceptor
Request.interceptors.request.use(
    config => {
        return config
    },
    error => {
        // do something with request error
        // console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
Request.interceptors.response.use(
    response => {
        const res = response.data
        if(response.status === 200) {
            if( typeof(res) === 'object' && 'permission' in res ) {
                if(res.permission === 'User') sessionStorage.setItem('prio', '0')
                else if(res.permission === 'Medical_point') sessionStorage.setItem('prio', '1')
                else if(res.permission === 'Root') sessionStorage.setItem('prio', '2')
            }
            return res
        }
        else {
            return res
        }
    },
    error => {
        // console.log(error,response) // for debug
        console.log(error)
        if(error.code === 'ERR_BAD_REQUEST') {
            ElMessage({
                message: 'Bad Request',
                type: 'error',
                duration: 3 * 1000
            })
        }
        else if(error.code === 'ERR_FORBIDDEN') {
            ElMessage({
                message: '权限错误',
                type: 'error',
                duration: 3 * 1000
            })
            ReLogin()
        }
        else {
            ElMessage({
                message: '服务器错误',
                type: 'error',
                duration: 3 * 1000
            })
            return Promise.reject(error)
        }
    }
)


export {Request}